<template>
  <div class="statistical-analysis-container">
    <!-- 顶部筛选条件 -->
    <div class="filter-bar">
      <div class="filter-item">
        <span class="label">开始时间：</span>
        <el-date-picker
          v-model="filterStartDate"
          type="date"
          placeholder="选择开始日期"
          value-format="yyyy-MM-dd"
          :picker-options="datePickerOptions"
          size="medium">
        </el-date-picker>
      </div>
      
      <div class="filter-item">
        <span class="label">结束时间：</span>
        <el-date-picker
          v-model="filterEndDate"
          type="date"
          placeholder="选择结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="datePickerOptions"
          size="medium">
        </el-date-picker>
      </div>
      
      <div class="filter-item">
        <span class="label">学院：</span>
        <el-select v-model="filterCollege" placeholder="请选择学院" clearable size="medium">
          <el-option
            v-for="college in colleges"
            :key="college"
            :label="college"
            :value="college">
          </el-option>
        </el-select>
      </div>
      
      <el-button type="primary" @click="handleQuery" size="medium">查询</el-button>
      <el-button @click="handleReset" size="medium">重置</el-button>
    </div>
    
    <!-- 四个图表区域 -->
    <el-row :gutter="20">
      <!-- 第一块：学院综合数据对比 -->
      <el-col :span="12">
        <el-card class="chart-block">
          <div slot="header" class="block-header">
            <span>学院综合数据</span>
            <el-checkbox-group v-model="selectedMetrics" @change="updateCollegeChart" size="small">
              <el-checkbox label="absenteeismRate">缺勤率</el-checkbox>
              <el-checkbox label="leaveRequests">请假人数</el-checkbox>
              <el-checkbox label="foodCarrying">带食物率</el-checkbox>
            </el-checkbox-group>
          </div>
          <div id="collegeCompare" class="chart-content"></div>
        </el-card>
      </el-col>
      
      <!-- 第二块：缺勤率最高的10个班 -->
      <el-col :span="12">
        <el-card class="chart-block">
          <div slot="header" class="block-header">
            <span>班级排名Top10（缺勤率）</span>
          </div>
          <div id="topAbsenteeismClasses" class="chart-content"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 第三块：各班级每月缺勤率对比 -->
      <el-col :span="12">
        <el-card class="chart-block">
          <div slot="header" class="block-header">
            <span>各班级月度趋势（缺勤率）</span>
            <div style="display: flex; gap: 10px;">
              <el-select 
                v-model="selectedClasses" 
                multiple 
                collapse-tags
                placeholder="选择班级对比" 
                size="small"
                style="width: 250px;"
                @change="updateMonthlyChart">
                <el-option
                  v-for="className in availableClasses"
                  :key="className"
                  :label="className"
                  :value="className">
                </el-option>
              </el-select>
            </div>
          </div>
          <div id="monthlyAbsenteeism" class="chart-content"></div>
        </el-card>
      </el-col>
      
      <!-- 第四块：老师授课班级缺勤率Top10 -->
      <el-col :span="12">
        <el-card class="chart-block">
          <div slot="header" class="block-header">
            <span>老师授课班级排名Top10（缺勤率）</span>
          </div>
          <div id="teacherAbsenteeismClasses" class="chart-content"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'StatisticAnalysis',
  data() {
    const now = new Date();
    const currentDate = now.toISOString().split('T')[0];
    const firstDayOfMonth = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-01`;
    
    return {
      // 筛选条件
      filterStartDate: firstDayOfMonth,
      filterEndDate: currentDate,
      filterCollege: '软件学院',
      
      // 学院列表
      colleges: [],
      
      // 图表指标选择
      selectedMetrics: ['absenteeismRate', 'leaveRequests', 'foodCarrying'],
      
      // 各图表选择的属性
      topClassesMetric: 'absenteeismRate',  // Top10班级的属性（只支持缺勤率）
      monthlyMetric: 'absenteeismRate',     // 月度趋势的属性
      teacherMetric: 'absenteeismRate',     // 老师班级的属性
      
      // 属性选项 - Top10班级只支持缺勤率
      topClassesMetricOptions: [
        { value: 'absenteeismRate', label: '缺勤率' }
      ],
      
      // 月度趋势和老师班级的属性选项
      metricOptions: [
        { value: 'absenteeismRate', label: '缺勤率' }
      ],
      
      // 月度对比-可选班级
      availableClasses: [],
      selectedClasses: [],
      
      // 图表数据
      collegeData: [],
      topClassesData: [],
      monthlyData: {},
      teacherClassesData: [],
      
      // 图表实例
      collegeChart: null,
      topClassesChart: null,
      monthlyChart: null,
      teacherClassesChart: null,
      
      // 日期选择器配置
      datePickerOptions: {
        disabledDate: (time) => {
          // 可以根据需要添加日期限制
          return false;
        }
      }
    }
  },
  
  created() {
    this.getAllColleges();
  },
  
  mounted() {
    window.addEventListener('resize', this.handleResize);
  },
  
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.collegeChart) this.collegeChart.dispose();
    if (this.topClassesChart) this.topClassesChart.dispose();
    if (this.monthlyChart) this.monthlyChart.dispose();
    if (this.teacherClassesChart) this.teacherClassesChart.dispose();
  },
  
  methods: {
    // 获取所有学院
    async getAllColleges() {
      try {
        const res = await this.$get('/api/course/getallcolleges');
        if (res.code === 200) {
          this.colleges = res.data || [];
          this.handleQuery();
        }
      } catch (error) {
        console.error('获取学院列表失败:', error);
        this.$message.error('获取学院列表失败');
      }
    },
    
    // 查询按钮
    handleQuery() {
      // 验证日期范围
      if (this.filterStartDate && this.filterEndDate) {
        if (new Date(this.filterStartDate) > new Date(this.filterEndDate)) {
          this.$message.error('开始时间不能晚于结束时间');
          return;
        }
      }
      
      this.getCollegeAnalysis();
      this.getTopAbsenteeismClasses();
      this.getMonthlyAbsenteeismRate();
      this.getTeacherAbsenteeismClasses();
    },
    
    // 重置按钮
    handleReset() {
      const now = new Date();
      const currentDate = now.toISOString().split('T')[0];
      const firstDayOfMonth = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-01`;
      
      this.filterStartDate = firstDayOfMonth;
      this.filterEndDate = currentDate;
      this.filterCollege = '';
      this.selectedClasses = [];
      this.handleQuery();
    },
    
    // 1. 获取学院综合分析数据
    async getCollegeAnalysis() {
      try {
        const { startDate, endDate } = this.getDateRange();
        const collegesToQuery = this.filterCollege ? [this.filterCollege] : this.colleges;
        
        const requests = collegesToQuery.map(college => {
          return this.$get('/api/course/getcollegecoursecnalysis', {
            startDate,
            endDate,
            college
          });
        });
        
        const results = await Promise.all(requests);
        
        this.collegeData = results.map((result, index) => {
          if (result.code === 200) {
            const data = {
              college: collegesToQuery[index],
              absenteeismRate: parseFloat((result.data.absenteeismRate && result.data.absenteeismRate.replace('%', '')) || 0),
              leaveRequests: parseInt(result.data.numberLeaveRequests || 0),
              foodCarrying: parseFloat((result.data.foodCarryingRate && result.data.foodCarryingRate.replace('%', '')) || 0)
            };

            return data;
          }
          return {
            college: collegesToQuery[index],
            absenteeismRate: 0,
            leaveRequests: 0,
            foodCarrying: 0
          };
        });
        
        this.updateCollegeChart();
      } catch (error) {
        console.error('获取学院分析数据失败:', error);
        this.$message.error('获取学院分析数据失败');
      }
    },
    
    // 2. 获取缺勤率最高的10个班
    async getTopAbsenteeismClasses() {
      try {
        const { startDate, endDate } = this.getDateRange();
        
        const res = await this.$get('/api/course/gethighestabsenteeismrate', {
          startDate,
          endDate,
          college: this.filterCollege || undefined
        });
        
        if (res.code === 200) {
          this.topClassesData = res.data || [];
          this.updateTopClassesChart();
        }
      } catch (error) {
        console.error('获取Top10班级失败:', error);
        this.$message.error('获取缺勤率最高班级数据失败');
      }
    },
    
    // 3. 获取各班级每月缺勤率
    async getMonthlyAbsenteeismRate() {
      try {
        // 从开始日期中提取年份，如果没有则使用当前年份
        const year = this.filterStartDate ? 
          parseInt(this.filterStartDate.split('-')[0]) : 
          new Date().getFullYear();
        
        const res = await this.$get('/api/course/getmonthlyabsenteeismrate', {
          year,
          college: this.filterCollege || undefined
        });
        
        if (res.code === 200) {
          this.monthlyData = res.data || {};
          this.availableClasses = Object.keys(this.monthlyData);
          
          if (this.selectedClasses.length === 0 && this.availableClasses.length > 0) {
            this.selectedClasses = this.availableClasses.slice(0, Math.min(5, this.availableClasses.length));
          }
          
          this.updateMonthlyChart();
        }
      } catch (error) {
        console.error('获取月度缺勤率失败:', error);
        this.$message.error('获取月度缺勤率数据失败');
      }
    },
    
    // 4. 获取老师授课班级缺勤率Top10
    async getTeacherAbsenteeismClasses() {
      try {
        // 从开始日期中提取年份和月份
        const startDate = this.filterStartDate; 
        let endDate =this.filterEndDate;
        
        const res = await this.$get('/api/course/getabsenceclassesbycollege', {
         startDate,
          endDate,
          college: this.filterCollege || undefined
        });
        
        if (res.code === 200) {
          this.teacherClassesData = res.data || [];
          this.updateTeacherClassesChart();
        }
      } catch (error) {
        console.error('获取老师班级缺勤率失败:', error);
        this.$message.error('获取老师班级缺勤率数据失败');
      }
    },
    
    // 获取日期范围
    getDateRange() {
      return { 
        startDate: this.filterStartDate || '', 
        endDate: this.filterEndDate || '' 
      };
    },
    
    // 更新学院对比图表
    updateCollegeChart() {
      const chartDom = document.getElementById('collegeCompare');
      if (!chartDom) return;
      
      if (!this.collegeChart) {
        this.collegeChart = echarts.init(chartDom);
      }
      
      const colleges = this.collegeData.map(item => item.college);
      const series = [];
      
      if (this.selectedMetrics.includes('absenteeismRate')) {
        series.push({
          name: '缺勤率(%)',
          type: 'bar',
          data: this.collegeData.map(item => item.absenteeismRate),
          itemStyle: { color: '#409EFF' }
        });
      }
      
      if (this.selectedMetrics.includes('leaveRequests')) {
        series.push({
          name: '请假人数',
          type: 'bar',
          data: this.collegeData.map(item => item.leaveRequests),
          itemStyle: { color: '#67C23A' }
        });
      }
      
      if (this.selectedMetrics.includes('foodCarrying')) {
        series.push({
          name: '带食物率(%)',
          type: 'bar',
          data: this.collegeData.map(item => item.foodCarrying),
          itemStyle: { color: '#E6A23C' }
        });
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        legend: {
          data: series.map(s => s.name),
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '12%',
          top: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: colleges
        },
        yAxis: {
          type: 'value'
        },
        series: series
      };
      
      this.collegeChart.setOption(option, true); // true表示清空之前的配置
    },
    
    // 更新Top10班级图表
    updateTopClassesChart() {
      const chartDom = document.getElementById('topAbsenteeismClasses');
      if (!chartDom) return;
      
      if (!this.topClassesChart) {
        this.topClassesChart = echarts.init(chartDom);
      }
      
      // 只支持缺勤率数据
      const config = {
        label: '缺勤率', 
        unit: '%', 
        color: '#F56C6C',
        formatter: '{c}%'
      };
      if(this.topClassesData!=null){
        this.topClassesData.reverse();
      }
      const classNames = this.topClassesData.map(item => item.className);
      const rates = this.topClassesData.map(item => 
        parseFloat((item.absenteeismRate && item.absenteeismRate.replace('%', '')) || 0)
      );
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: `{b}: ${config.formatter}`
        },
        grid: {
          left: '8%',
          right: '10%',
          bottom: '8%',
          top: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: config.label,
          axisLabel: {
            formatter: `{value}${config.unit}`
          }
        },
        yAxis: {
          type: 'category',
          data: classNames,
          axisLabel: {
            interval: 0
          }
        },
        series: [{
          type: 'bar',
          data: rates,
          itemStyle: {
            color: config.color
          },
          label: {
            show: true,
            position: 'right',
            formatter: config.formatter
          }
        }]
      };
      
      this.topClassesChart.setOption(option);
    },
    
 // 更新月度对比图表
updateMonthlyChart() {
  const chartDom = document.getElementById('monthlyAbsenteeism');
  if (!chartDom) return;
  
  if (!this.monthlyChart) {
    this.monthlyChart = echarts.init(chartDom);
  }
  
  // 只支持缺勤率数据
  const config = {
    label: '缺勤率', 
    unit: '%', 
    dataKey: 'absenceRate'
  };
  
  // 过滤掉未选中的班级数据
  const filteredClasses = this.selectedClasses.filter(className => 
    this.monthlyData[className] && this.monthlyData[className].length > 0
  );
  
  const series = filteredClasses.map(className => {
    const classData = this.monthlyData[className] || [];
    const sortedData = classData.sort((a, b) => a.month - b.month);
    
    return {
      name: className,
      type: 'line',
      data: sortedData.map(item => [item.month, item.absenceRate || 0]),
      smooth: true,
      symbol: 'circle',
      symbolSize: 6
    };
  });
  
  // 处理没有选中班级或无数据的情况
  if (this.selectedClasses.length === 0 || series.length === 0) {
    this.monthlyChart.setOption({
      // 完全清空系列数据
      series: [],
      // 清空图例
      legend: {
        data: []
      },
      // 显示空状态提示
      title: {
        text: '未选择班级或无数据',
        left: 'center',
        top: '40%',
        textStyle: {
          color: '#909399',
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      // 显示提示说明
      graphic: [
        {
          type: 'text',
          left: 'center',
          top: '50%',
          style: {
            text: '请选择班级进行对比分析',
            fill: '#909399',
            fontSize: 14
          }
        }
      ]
    }, true); // 使用notMerge: true强制更新
    return;
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let result = `${params[0].value[0]}月<br/>`;
        params.forEach(item => {
          result += `${item.seriesName}: ${item.value[1]}${config.unit}<br/>`;
        });
        return result;
      }
    },
    legend: {
      data: filteredClasses,
      type: 'scroll',
      bottom: 0,
      itemWidth: 14,
      itemHeight: 14,
      textStyle: {
        fontSize: 12
      }
    },
    grid: {
      left: '8%',
      right: '8%',
      bottom: '20%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '月份',
      min: 1,
      max: 12,
      interval: 1,
      axisLabel: {
        formatter: '{value}月',
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      name: `${config.label}(${config.unit})`,
      axisLabel: {
        formatter: `{value}${config.unit}`
      }
    },
    series: series
  };
  
  this.monthlyChart.setOption(option, true);
},
    
    // 更新老师班级缺勤率图表
    updateTeacherClassesChart() {
      const chartDom = document.getElementById('teacherAbsenteeismClasses');
      if (!chartDom) return;
      
      if (!this.teacherClassesChart) {
        this.teacherClassesChart = echarts.init(chartDom);
      }
      
      // 只支持缺勤率数据
      const config = {
        label: '缺勤率', 
        unit: '%', 
        color: '#F56C6C',
        formatter: '{c}%'
      };
      const teacherName = this.teacherClassesData.map(item => item.teacherName+"_"+item.className|| '');
      const Class=this.teacherClassesData.map(item => item.className || '')
      const rates = this.teacherClassesData.map(item => 
        parseFloat((item.absenceRate && String(item.absenceRate).replace('%', '')) || item.rate || 0)
      );
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: `{b}: ${config.formatter}`
        },
        grid: {
          left: '8%',
          right: '10%',
          bottom: '8%',
          top: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: config.label,
          axisLabel: {
            formatter: `{value}${config.unit}`
          }
        },
        yAxis: {
          type: 'category',
          data: teacherName,
          inverse: true,
          axisLabel: {
            interval: 0
          }
        },
        series: [{
          type: 'bar',
          data: rates,
          itemStyle: {
            color: config.color
          },
          label: {
            show: true,
            position: 'right',
            formatter: config.formatter
          }
        }]
      };
      
      this.teacherClassesChart.setOption(option);
    },
    
    // 处理窗口大小变化
    handleResize() {
      if (this.collegeChart) this.collegeChart.resize();
      if (this.topClassesChart) this.topClassesChart.resize();
      if (this.monthlyChart) this.monthlyChart.resize();
      if (this.teacherClassesChart) this.teacherClassesChart.resize();
    }
  }
}
</script>

<style scoped>
.statistical-analysis-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

/* 顶部筛选条件栏 */
.filter-bar {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  gap: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-item .label {
  margin-right: 10px;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.filter-item .el-date-picker,
.filter-item .el-select {
  width: 200px;
}

/* 图表块 */
.chart-block {
  height: 450px;
  margin-bottom: 0;
}

.chart-block >>> .el-card__header {
  padding: 15px 20px;
  background: #fafafa;
  border-bottom: 1px solid #ebeef5;
}

.block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chart-block >>> .el-card__body {
  padding: 20px;
  height: calc(100% - 56px);
}

.chart-content {
  width: 100%;
  height: 100%;
}

/* 复选框组样式 */
.el-checkbox-group {
  display: flex;
  gap: 15px;
}
</style>
